package com.st.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>title: com.wfx.filters</p>
 * author zhuximing
 * description:网关的全局认证的过滤器
 */

public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        //获取jwt令牌
        String jwtToken = exchange.getRequest().getHeaders().getFirst("token");
        if (jwtToken == null) {

            //不能放行，直接返回，返回json信息
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

            Map res = new HashMap(){{
                put("success",false);
                put("msg","必须指定token");
            }};

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = null;
            try {
                jsonStr = objectMapper.writeValueAsString(res);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }


            DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

            return response.writeWith(Flux.just(dataBuffer));//响应json数据


        }else{
            //校验令牌
           if( jwtToken.equals("xx")){//校验成功
              return   chain.filter(exchange);  //放行
           }else{

               //不能放行，直接返回，返回json信息
               response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

               Map res = new HashMap(){{
                   put("success",false);
                   put("msg","令牌不合法");
               }};

               ObjectMapper objectMapper = new ObjectMapper();
               String jsonStr = null;
               try {
                   jsonStr = objectMapper.writeValueAsString(res);
               } catch (JsonProcessingException e) {
                   e.printStackTrace();
               }


               DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

               return response.writeWith(Flux.just(dataBuffer));//响应json数据
           }
        }


    }


    //指定过滤器的执行顺序，值越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
